<template>
  <div class="class-student-container">
    <!-- 顶部导航区 -->
    <div class="top-bar">
      <el-button type="primary" icon="ArrowLeft" @click="handleBack">返回</el-button>
      <h2 class="class-title">班级名称：{{ className }}</h2>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <!-- 左侧：班级内学生 -->
      <div class="table-section">
        <div class="search-area">
          <el-input
            v-model="leftSearch" 
            placeholder="搜索学生姓名"
            prefix-icon="Search"
            class="search-input"
            @input="handleLeftSearch"
          ></el-input>
        </div>
        <el-table
          :data="filteredClassStudents"
          border
          stripe
          style="width: 100%; max-height: 400px; overflow-y: auto;"
        >
          <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
          <el-table-column prop="studentId" label="学号" width="120" align="center"></el-table-column>
          <el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
          <el-table-column prop="gender" label="性别" width="80" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.gender === '男'" type="info">男</el-tag>
              <el-tag v-else type="danger">女</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="age" label="年龄" width="80" align="center"></el-table-column>
          <el-table-column prop="course" label="课程" width="120" align="center"></el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button type="danger" size="small" @click="removeStudent(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 右侧：所有学生 -->
      <div class="table-section">
        <div class="search-area">
          <el-input
            v-model="rightSearch"
            placeholder="搜索学生姓名"
            prefix-icon="Search"
            class="search-input"
            @input="handleRightSearch"
          ></el-input>
          <el-button type="primary" @click="addSelectedStudents">添加选中学生</el-button>
        </div>
        <el-table
          :data="filteredAllStudents"
          border
          stripe
          style="width: 100%; max-height: 400px; overflow-y: auto;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" :selectable="isStudentSelectable"></el-table-column>
          <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
          <el-table-column prop="studentId" label="学号" width="120" align="center"></el-table-column>
          <el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
          <el-table-column prop="gender" label="性别" width="80" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.gender === '男'" type="info">男</el-tag>
              <el-tag v-else type="danger">女</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="age" label="年龄" width="80" align="center"></el-table-column>
          <el-table-column prop="course" label="课程" width="120" align="center"></el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

// 路由和导航
const route = useRoute();
const router = useRouter();

// 班级名称（实际应用中应从路由参数或API获取）
const className = ref('高一(1)班');

// 搜索关键词
const leftSearch = ref('');
const rightSearch = ref('');

// 选中的学生（右侧表格）
const selectedStudents = ref([]);

// 模拟数据 - 班级学生（左侧表格）
const classStudents = ref([]);

// 模拟数据 - 所有学生（右侧表格）
const allStudents = ref([]);

// 生成模拟学生数据
const generateMockStudents = (count) => {
  const courses = ['高等数学', '线性代数', '计算机基础', '程序设计', '数据结构'];
  return Array.from({ length: count }, (_, i) => ({
    id: i + 1,
    studentId: `2023${(i + 1000).toString().slice(-4)}`,
    name: `学生${i + 1}`,
    gender: Math.random() > 0.5 ? '男' : '女',
    age: 16 + Math.floor(Math.random() * 3),
    course: courses[Math.floor(Math.random() * courses.length)]
  }));
};

// 初始化数据
onMounted(() => {
  // 生成30个学生模拟数据
  const students = generateMockStudents(30);
  // 随机选择5个学生作为班级初始学生
  const initialClassStudents = students.sort(() => 0.5 - Math.random()).slice(0, 5);
  classStudents.value = initialClassStudents;
  // 剩下的作为其他学生
  allStudents.value = students.filter(student => !initialClassStudents.some(cs => cs.id === student.id));
});

// 左侧表格过滤后的数据
const filteredClassStudents = computed(() => {
  return classStudents.value.filter(student =>
    student.name.toLowerCase().includes(leftSearch.value.toLowerCase())
  );
});

// 右侧表格过滤后的数据
const filteredAllStudents = computed(() => {
  return allStudents.value.filter(student =>
    student.name.toLowerCase().includes(rightSearch.value.toLowerCase())
  );
});

// 判断学生是否可选（不在班级中）
const isStudentSelectable = (row) => {
  return !classStudents.value.some(student => student.id === row.id);
};

// 处理搜索变化
const handleLeftSearch = () => { /* 由computed自动处理 */ };
const handleRightSearch = () => { /* 由computed自动处理 */ };

// 处理右侧表格选择变化
const handleSelectionChange = (val) => {
  selectedStudents.value = val;
};

// 添加选中的学生到班级
const addSelectedStudents = () => {
  if (selectedStudents.value.length === 0) {
    ElMessage.warning('请先选择要添加的学生');
    return;
  }

  // 将选中的学生添加到班级
  selectedStudents.value.forEach(student => {
    classStudents.value.push(student);
    // 从所有学生中删除
    const index = allStudents.value.findIndex(s => s.id === student.id);
    if (index !== -1) {
      allStudents.value.splice(index, 1);
    }
  });

  // 清空选择
  selectedStudents.value = [];
  ElMessage.success(`成功添加${selectedStudents.value.length}名学生到班级`);
};

// 从班级删除学生
const removeStudent = (student) => {
  // 从班级学生中删除
  const index = classStudents.value.findIndex(s => s.id === student.id);
  if (index !== -1) {
    classStudents.value.splice(index, 1);
  }

  // 将学生添加回所有学生列表
  allStudents.value.push(student);
  ElMessage.success(`已将${student.name}从班级中删除`);
};

// 返回按钮
const handleBack = () => {
  router.push('/classManage');
};
</script>

<style scoped>
.class-student-container {
  padding: 20px;
}

.top-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.class-title {
  flex: 1;
  text-align: center;
  margin: 0;
}

.table-container {
  display: flex;
  gap: 20px;
}

.table-section {
  flex: 1;
}

.search-area {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}
</style>